<template>
  <div class="page-content">
    <!-- 生产统计下的页面每个页面都要引入这个组件 -->
    <dovecote-info></dovecote-info>
    <!-- 增删改查页面都要引入这个组件 -->
    <table-bar :showTop="false"
               ref="table"
               :columns="columns"
               @changeColumn="changeColumn">
      <!-- 筛选栏 -->
      <div slot="top">
        <el-form label-width="70px">
          <el-row :gutter="40">
            <el-col :xs="24"
                    :sm="12"
                    :lg="6">
              <el-form-item label="月份：">
                <el-date-picker v-model="query.date"
                                @change="selectDate"
                                type="month"
                                format="yyyy 年 MM 月"
                                value-format="yyyy-MM"
                                :clearable="false">
                </el-date-picker>
              </el-form-item>

            </el-col>

            <el-col :xs="24"
                    :sm="12"
                    :lg="6">
              <el-form-item label="饲料类型">
                <el-input placeholder="根据饲料类型筛选"
                          clearable
                          v-model="query.keyWords"></el-input>
              </el-form-item>
            </el-col>

            <el-row :xs="24"
                    :sm="12"
                    :lg="6"
                    style="float: right; margin-right: 10px;">
              <el-button type="primary"
                         @click="feedSearch">搜索</el-button>
              <el-button @click="getMonthlyStatementReport">重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>
      <div slot="bottom">
        <!-- <el-button type="primary"
                   plain
                   @click="showDialog('add')">新增用户</el-button>
        <el-button type="danger"
                   plain
                   @click="showDialog('add')">批量删除</el-button> -->
        <el-button type="success"
                   plain
                   @click="showDialog('add')">导入</el-button>
        <el-button type="success"
                   plain
                   @click="showDialog('add')">导出</el-button>
      </div>
    </table-bar>

    <!-- 表格内容 -->
    <the-table :data="reportList">
      <el-table-column type="selection"
                       width="55"></el-table-column>
      <el-table-column label="鸽棚"
                       prop="dovecoteNumber"
                       v-if="columns[0].show">
      </el-table-column>
      <el-table-column label="饲料类型"
                       prop="feedType"
                       v-if="columns[1].show" />
      <el-table-column label="规格"
                       prop="specifications"
                       v-if="columns[2].show" />
      <el-table-column label="库存量"
                       prop="stockAmount"
                       v-if="columns[3].show" />
      <el-table-column label="使用量"
                       prop="useAmount"
                       v-if="columns[4].show">
      </el-table-column>
      <el-table-column label="创建时间"
                       prop="gmtCreate"
                       min-width="100px"
                       v-if="columns[5].show" />
      <el-table-column label="剩余数量"
                       v-if="columns[6].show">
        <template slot-scope="scope">
          <!-- 标签按钮和输入框 -->
          <el-input v-if="scope.row.inputVisible"
                    :placeholder="scope.row.amount"
                    v-model.number.trim="scope.row.inputValue"
                    ref="inputRef"
                    size="small"
                    class="inputWith"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)">
          </el-input>
          <el-tag v-else
                  size="small"
                  type="primary"
                  class="countTag">{{scope.row.amount}}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column fixed="right"
                       label="操作"
                       width="150px"
                       v-if="columns[7].show">
        <template slot-scope="scope">
          <el-button type="text"
                     icon="el-icon-edit"
                     @click="showInput(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </the-table>
    <!-- 表格内容 -->
    <!-- 分页器区域 -->
    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   :page-sizes="[5, 10, 25, 50]"
                   layout="total, sizes, prev, pager, next, jumper"
                   :page-size="query.pageSize"
                   :current-page="query.pageNum"
                   :total="total">
    </el-pagination>
  </div>

</template>

<script>
import tipBtn from '@common/TipButton.vue'
import DovecoteInfo from '@common/DovecoteInfo.vue';

export default {
  name: 'FMouthChart',
  meta: {
    title: '月结报表'
  },
  created () {
    //获取当前日期
    this.getNowDate()
    //获取报表
    this.getMonthlyStatementReport()
    // 获取鸽棚列表
    this.getAllDovecoteNumber()
  },
  data () {
    return {
      //顶部选择器选项
      options: [],
      // 查询参数
      query: {
        selectVal: '',//选择器绑定值
        keyWords: '',// 顶部搜索框
        date: '',//指定月份
        // 分页器数据
        pageNum: 1,// 当前选中页码
        pageSize: 5,//当前页大小
        baseId: 3//基地id
      },
      // 数据总数
      total: 0,
      // 剩余数量编辑标志位
      isEditing: false,
      // 表格数据源
      reportList: [],
      reportList_old: [{
        "id": "31",
        "baseId": "12",
        "dovecoteNumber": "A01",
        "feedType": "李四牌饲料",
        "stockAmount": 200,
        "useAmount": 150,
        "amount": 50,
        "specifications": "500kg/袋",
        "gmtCreate": "2021-08-07 00:00:00",
        "gmtModified": "2021-09-07 23:33:49",
        inputVisible: false,

      }, {
        "id": "31",
        "baseId": "12",
        "dovecoteNumber": "A01",
        "feedType": "李四牌饲料",
        "stockAmount": 200,
        "useAmount": 150,
        "amount": 50,
        "specifications": "500kg/袋",
        "gmtCreate": "2021-08-07 00:00:00",
        "gmtModified": "2021-09-07 23:33:49",
        inputVisible: false,

      }],
      columns: [
        { name: "鸽棚", show: true },
        { name: "饲料类型", show: true },
        { name: "规格", show: true },
        { name: "库存量", show: true },
        { name: "使用量", show: true },
        { name: "创建时间", show: true },
        { name: "剩余数量", show: true },
        { name: "操作", show: true },
      ]
    }
  },
  computed: {
    baseInfo () {
      console.log(this.$store.state.Usersetting.BaseInfo);
      return this.$store.state.Usersetting.BaseInfo
    },
    currentDovecote () {
      return this.$store.state.Usersetting.CurrentDovecote
    }
  },
  methods: {
    // 获取月结报表
    async getMonthlyStatementReport (feedType = '', dovecoteNumber = '') {
      // Request URL: http://localhost:8080/breed/feedStock/getMonthlyStatementReport/1/5?baseId=3&month=2021-9-01&feedType=&dovecoteNumber=

      // &feedType=&dovecoteNumber= 参数为空会查不到数据
      const params = {
        baseId: this.query.baseId,
        month: this.query.date + '-01',//拼接具体完整日期方便后端查询
      }
      // 如果有传入则追加属性
      if (feedType) params.feedType = feedType
      if (dovecoteNumber) params.dovecoteNumber = dovecoteNumber




      const { data: res } = await this.$http.get(`/breed/feedStock/getMonthlyStatementReport/${this.query.pageNum}/${this.query.pageSize}`, { params })

      console.log('[ 获取月结报表 res ] >', res)

      if (res.statusCode !== 20000) return this.$message.error('数据获取失败')


      //为data添加属性
      res.data.records.forEach(item => item.inputVisible = false)


      //保存数据
      this.reportList = res.data.records
      this.total = res.data.total


    },
    //获取所有鸽棚编号
    async getAllDovecoteNumber () {
      const { data: res } = await this.$http.get('/breed/dovecote/getAllDovecoteNumber', { params: { baseId: this.query.baseId } })

      if (res.statusCode !== 20000) return this.$message.error('获取所有鸽棚编号失败')
      // console.log('获取所有鸽棚编号', res);
      //保存
      const options = []
      res.data.forEach(x => {
        options.push({
          label: x,
          value: x
        })
      })
      this.options = options
    },
    // 监听下拉框 鸽棚选中
    async handleSelect (dovecoteNumber) {
      //获取鸽棚id
      console.log('[ handleSelect ] >', dovecoteNumber)

      // 复用获取列表函数
      this.getMonthlyStatementReport('', this.query.selectVal)

    },
    // 监听下拉框清空
    handleSelectClear () {
      this.query.selectVal = ''
      // this.getMonthlyStatementReport()
    },
    //搜索框搜索
    async feedSearch () {
      if (this.query.keyWords.length <= 0) {
        return this.$message.error('您还未输入关键词')
      }
      // 复用获取列表函数
      this.getMonthlyStatementReport(this.query.keyWords)

      //发送请求获取数据
      // const { data: res } = await this.$http.post('/breed/feedStock/get', { feedType: this.query.keyWords })
      // console.log(res);
      // if (res.statusCode !== 20000) return this.$message.error('查询失败')
      // this.$message.success('查询成功')


      //为data添加属性
      // res.data.forEach(item => item.inputVisible = false)
      // //保存数据
      // this.reportList = res.data
      // this.total = res.data.total


      // 清空输入框
      this.query.keyWords = ''
    },
    //获取当前日期
    getNowDate (target = '') {
      // console.log('获取当前日期');
      //获取当前年的上月份
      const now = new Date()
      const date = `${now.getFullYear()}-${now.getMonth()}`
      // 无参数则返回当前日期
      if (!target) {
        this.query.date = date
        return true;
      }
      // 返回参数是否超出当前日期
      const [now_y, now_m] = date.split('-')
      const [target_y, target_m] = target.split('-')
      console.log(now_y, now_m)
      console.log(target_y, target_m)
      // 年份是否超前
      if (now_y * 1 > target_y * 1) return true;


      else if (now_y * 1 === target_y * 1 && now_m * 1 >= target_m * 1) return true;


      else {
        //重置为默认时间
        this.query.date = date
        this.$message.error('该月份的报表尚未出炉')
        return false
      }


    },
    //日期选择器选中
    async selectDate () {
      //日期合法检验
      console.log(this.getNowDate(this.query.date));
      if (!this.getNowDate(this.query.date)) {
        return;
      }
      //发送请求查询某月报表
      const { data: res } = await this.$http.get(`/breed/feedStock/getMonthlyStatementReport/${this.query.pageNum}/${this.query.pageSize}`, {
        params: {
          baseId: this.query.baseId,
          month: this.query.date + '-01'
        }
      })
      // console.log('日期查询res', res);

      if (res.statusCode !== 20000) return this.$message.error('查找失败')



      //为data添加属性
      res.data.records.forEach(item => item.inputVisible = false)

      //保存数据
      this.reportList = res.data.records
      this.total = res.data.total

      if (res.data.records.length === 0)
        return this.$message.success('查找成功但无记录')
      this.$message.success('查找成功')






    },
    //展示剩余数量输入框
    showInput (row) {
      if (!this.isEditing) {
        row.inputVisible = true
        this.isEditing = true
        //渲染完成后获取
        this.$nextTick(_ => {
          console.log(this.$refs.inputRef);
          // 让文本框自动获取焦点
          this.$refs.inputRef.focus()
        })
      }


    },
    //输入框修改数据
    handleInputConfirm (row) {
      if (row.inputValue < 0 || !row.inputValue) {
        return this.$message.error('请填入正确的数量')
      }

      this.$confirm(`此操作将修改剩余数量为${row.inputValue}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //保存输入的数量
        row.amount = row.inputValue
        console.log('[ row ] >', row.id)
        //发送修改请求
        const { data: res } = await this.$http.post(`/breed/feedStock/updateResidue/${row.id}?residue=${row.amount}`)
        // const { data: res } = await this.$http.post('/breed/feedStock/updateResidue/' + row.id, { residue: row.amount })

        console.log('[ 修改数量 res ] >', res)

        if (res.statusCode !== 20000)
          return this.$message.error('修改失败')
        this.$message.success('修改成功')
        // 重新获取报表数据
        this.getMonthlyStatementReport()


        // 等待保存输入的数量后清空文本框
        row.inputValue = ''
      }).catch(() => {
        this.$message('已取消修改!')
        // 清空文本框
        row.inputValue = ''
      })

      // 隐藏
      row.inputVisible = false
      this.isEditing = false
    },


    // 分页器监听
    handleSizeChange (newPageSize) {
      this.query.pageSize = newPageSize
      this.getMonthlyStatementReport()
      // console.log('[ newPageSize ] >', newPageSize)
    },
    handleCurrentChange (newPageNum) {
      this.query.pageNum = newPageNum
      this.getMonthlyStatementReport()


      // console.log('[ newPageNum ] >', newPageNum)
    },
    //筛选列
    changeColumn (columns) {
      this.columns = columns
      this.$refs.table.doLayout()
    }


  },
  // 注册通用组件
  components: {
    tipBtn,
    DovecoteInfo
  }
}

</script>

<style lang="scss" scoped>
.el-pagination {
  margin-top: 6px;
  text-align: center;
}
.table-content {
  margin-top: 15px;
}

.countTag {
  text-align: center;
  min-width: 60px;
  height: 30px;
  line-height: 30px;
}
.inputWith {
  max-width: 60px;
  min-width: 60px;
  // width: 60px;
}

.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 210px;
}
</style>
